#! /usr/bin/env python
# -*- coding: utf-8 -*-

import json
import requests
from flask import current_app
from flask_babel import _


def translate(text, source_language, dest_language):
    TRANSLATE_API_URL = "https://fanyi.baidu.com/transapi?from={}&to={}&query={}"

    # if source_language == None:
    #     source_language = "auto"
    source_language = "auto"
    dest_language = dest_language[:2]

    r = requests.get(TRANSLATE_API_URL.format(source_language, dest_language, text))
    if r.status_code != 200:
        return _('Error: the translation service failed.')

    response = json.loads(r.content.decode('utf-8-sig'))

    if "error" in response.keys():
        current_app.logger.info(f"{r.text}, src: {source_language}, dst: {dest_language}, text: {text}")
        return _('Error: the translation service failed.')

    return response["data"][0]["dst"]
